/*
 * Copyright (c) 2013 Andaily Information Technology Co. Ltd
 * www.andaily.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Andaily Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with Andaily Information Technology Co. Ltd.
 */
package top.suven.http.oauth.validator;


import top.suven.http.oauth.vo.OAuthParameter;
import org.apache.oltu.oauth2.as.request.AbstractOAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *
 * authorization_code 的实现类
 * grant_type=authorization_code
 * 2018-08-01
 * <p/>
 *  AbstractOauthTokenValidator
 *  *  客户端	客户详细资料 抽像模块类，用于公共验证和获取客户用户的信息；
 *  * 将通用的行为(方法) 位于此
 * 1.授权码模式（authorization code）
 * @author suven.wang
 */

/**
 * /oauth/token?client_id=unity-client&client_secret=unity&grant_type=authorization_code&code=zLl170&redirect_uri=redirect_uri
 */

public class GrantTypeAuthorizationCodeValidator extends AbstractOauthGrantTypeValidator {

    private static final Logger logger = LoggerFactory.getLogger(GrantTypeAuthorizationCodeValidator.class);


    public GrantTypeAuthorizationCodeValidator(AbstractOAuthTokenRequest oauthRequest) {

        super(oauthRequest);
    }

    /**
     * /oauth/token?client_id=unity-client&client_secret=unity&grant_type=authorization_code&code=zLl170&redirect_uri=redirect_uri
     */

    @Override
    protected boolean validateSelf() throws OAuthSystemException {
        // 前4点 基于token 验证于AbstractOauthTokenValidator 抽象
        if(!this.validateGrantType()){
            return false;
        }
        if(! this.validateClientSecret()){
            return false;
        }
        ////验证类型，有AUTHORIZATION_CODE/PASSWORD/REFRESH_TOKEN/CLIENT_CREDENTIALS
        //to do by db 从数据库查出数据,OauthCode的实现
        //validate code
       if(! this.validateCodeResponse()){
            return false;
       }
        if(!validateAccessToken(getUserId())){
            return false;
        }
        return true;

    }

    private boolean validateCodeResponse() throws OAuthSystemException {
        final String authCode = getCode();
        final long userId = getUserId();
        final String clientId = getClientId();
        final String state = getState();
        OAuthParameter parameter = OAuthParameter.build()
                .setUserId(userId)
                .setCode(authCode)
                .setClientId(clientId)
                .setState(state);
        boolean isCode = oauthService.checkAuthorizationCode(parameter);
        if(isCode){
            return isCode;
        }
        this.setResponse( invalidCodeResponse(authCode));
        return false;

    }




}
